﻿using EM.FrameWork.Paging;
using EM.OA.BLL;
using EM.OA.Common;
using EM.OA.DataModel.DBModel;
using EM.OA.Portal.Models;
using EM.OA.WebCommon;
using EM.OA.WebCommon.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;

namespace EM.OA.Portal.Controllers
{
    public class CarApplyController : BaseAuthController
    {

        #region 预约
        /// <summary>
        /// 返回Index视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CreatApplyList(Guid carID)
        {
            XElement xTable = new XElement("table", new XAttribute("id", "xbgd"), new XAttribute("style", "width:100%;text-align:center"), new XAttribute("border", "1"), new XAttribute("cellspacing", "0"), new XAttribute("cellpadding", "5"));
            #region 表头
            XElement xhead = new XElement("tr", new XElement("td", "车牌号码"), new XElement("td", "日期"));

            for (int i = 0; i < 23; i++)
            {
                XElement xtime = null;
                DateTime time = DateTime.Parse("2000-12-31 00:00:00");
                xtime = new XElement("td", new XAttribute("style", "width:35px"), time.AddHours(i).ToShortTimeString() + "<br />" + time.AddHours(i + 1).ToShortTimeString());
                xhead.Add(xtime);
            }
            xTable.Add(xhead);
            #endregion

            #region 列表

            for (int i = 0; i < 7; i++)
            {
                XElement xtr = null;
                xtr = new XElement("tr");
                string carNumber = string.Empty;
                if (i == 0)
                {
                    CarInfoBLL bll = new CarInfoBLL();
                    carNumber = bll.GetEntity(carID).CarNumber;
                    xtr.Add(new XElement("td", carNumber, new XAttribute("rowspan", 7)));
                }

                DateTime date = DateTime.Parse(DateTime.Now.AddDays(i).ToString("yyyy-MM-dd 00:00:00"));
                xtr.Add(new XElement("td", date.ToString("yyyy-MM-dd")));
                List<EMOA_CarApply> list = new List<EMOA_CarApply>();
                CarApplyBLL applyBll = new CarApplyBLL();
                list = applyBll.GetList(p => p.CarID == carID && p.ApplyStartTime >= date && p.ApplyEndTime < date.AddDays(1));

                for (int j = 0; j < 23; j++)
                {
                    DateTime time = DateTime.Parse(date.ToString("yyyy-MM-dd") + " 00:00:00");
                    DateTime start = time.AddHours(j);
                    //DateTime end = time.AddMinutes(30 * (i + 1));
                    XElement xtd = null;
                    if (list.Where(p => p.ApplyStartTime == start && p.Status != (int)GlobalEnum.MeetingApplyStatus.Fail).Count() > 0)
                    {
                        DateTime end = list.Where(p => p.ApplyStartTime == start).Single().ApplyEndTime;
                        string status = list.Where(p => p.ApplyStartTime == start).Single().Status.ToString();

                        TimeSpan ts1 = new TimeSpan(start.Ticks);
                        TimeSpan ts2 = new TimeSpan(end.Ticks);
                        TimeSpan ts = ts1.Subtract(ts2).Duration();

                        int num = Convert.ToInt32(ts.TotalHours);

                        string scr = string.Empty;
                        string onclickMethod = string.Empty;
                        if (int.Parse(status) == (int)GlobalEnum.MeetingApplyStatus.Success)
                        {
                            scr = "../Images/xinglsb.gif";
                        }
                        else if (int.Parse(status) == (int)GlobalEnum.MeetingApplyStatus.Appling)
                        {
                            scr = "../Images/xingcsb.gif";
                        }
                        else if (int.Parse(status) == (int)GlobalEnum.MeetingApplyStatus.Fail)//暂时不会用到
                            scr = "../Images/xingrsb.gif";
                        XElement ximg = new XElement("img", new XAttribute("src", scr),
                            new XAttribute("width", "19"), new XAttribute("height", "18"), new XAttribute("onclick", onclickMethod));
                        //<a href="#" onclick="open"></a>

                        XElement xa = new XElement("a", new XAttribute("href", "#"), new XAttribute("onclick", onclickMethod));
                        xa.Add(ximg);
                        xtd = new XElement("td", ximg, new XAttribute("colspan", num));
                        j = j + num - 1;
                    }
                    else
                    {
                        string dataquery = string.Empty;
                        dataquery = "{" + string.Format("q_ApplyDate:'{0}',q_StartTime:'{1}',q_EndTime:'{2}'",
                            date.ToString("yyyy-MM-dd"),
                            time.AddHours(j).ToShortTimeString(),
                            time.AddHours(j + 1).ToShortTimeString()) + "}";

                        string onclickMethod = string.Empty;
                        onclickMethod = "apply(" + dataquery + ")";

                        XElement ximg = new XElement("img", new XAttribute("src", "../Images/xinghsb.gif"), new XAttribute("width", "19"), new XAttribute("height", "18"), new XAttribute("onclick", onclickMethod));
                        XElement xa = new XElement("a", new XAttribute("href", "#"), new XAttribute("target", "_self"), new XAttribute("onclick", onclickMethod));
                        xa.Add(ximg);
                        xtd = new XElement("td", ximg);
                    }

                    xtr.Add(xtd);
                }
                xTable.Add(xtr);
            }

            #endregion
            return Content(xTable.ToString().Replace("&lt;", "<").Replace("&gt;", ">"));
        }

        
        /// <summary>
        /// 增加实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(CarApplyModels model)
        {
            try
            {
                //if (ModelState.IsValid)
                //{
                    CarApplyBLL bll = new CarApplyBLL();
                    EMOA_CarApply entity = model.ToEntity<EMOA_CarApply>();
                    entity.ApplyStartTime = DateTime.Parse(model.ApplyDate.Value.ToShortDateString() + " " + model.ApplyStartTime2);
                    entity.ApplyEndTime = DateTime.Parse(model.ApplyDate.Value.ToShortDateString() + " " + model.ApplyEndTime2);
                    entity.ApplyID = Guid.NewGuid();
                    entity.CreateBy = CurrentUser.UserID;
                    entity.CreateTime = DateTime.Now;
                    entity.UseCarPersonID = CurrentUser.UserID;
                    entity.Status = (int)GlobalEnum.CarApplyStatus.Appling;
                    if (bll.Add(entity))
                    {
                        return Content("OK");
                    }
                    else
                    {
                        return Content("增加失败");
                    }
                //}
                //else
                //    return Content("验证失败");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        #endregion

        #region 审核
        public ActionResult Check()
        {
            return View();
        }

        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Check(CarApplyModels model)
        {
            try
            {
                //if (ModelState.IsValid)
                //{
                    CarApplyBLL bll = new CarApplyBLL();
                    EMOA_CarApply entity = bll.GetEntity(model.ApplyID);
                    entity.Status = model.Status;
                    entity.ApprovalRemark = Server.HtmlDecode(model.ApprovalRemark); 
                    entity.UpdateBy = CurrentUser.UserID;
                    entity.UpdateTime = DateTime.Now;
                    entity.ApprovalTime = DateTime.Now;
                    if (bll.Update(entity))
                        return Content("OK");
                    else
                        return Content("修改失败");
                //}
                //else
                //{
                //    return Content("验证失败");
                //}
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        public JsonResult GetList(string page, string rows)
        {
            string _status = GetParam("j_status");
            string _applyUserID = GetParam("j_applyUserID");
            string _applyDate = GetParam("j_applyDate");
            string _startTime = GetParam("j_startTime");
            string _endTime = GetParam("j_endTime");

            DateTime? _Start = null;
            DateTime? _End = null;

            if (_applyDate.IsNotEmpty())
            {
                if (_startTime.IsNotEmpty())
                    _Start = DateTime.Parse(_applyDate + " " + _startTime);
                if (_endTime.IsNotEmpty())
                    _End = DateTime.Parse(_applyDate + " " + _endTime);
            }

            List<object> result = new List<object>();
            CarApplyBLL bll = new CarApplyBLL();
            PagedList<EMOA_CarApply> list = bll.GetPagedList(Convert.ToInt32(page), Convert.ToInt32(rows),
                p => (_status.IsNullOrEmpty() || p.Status == Convert.ToInt32(_status)) &&
                (_applyUserID.IsNullOrEmpty() || p.UseCarPersonID == Guid.Parse(_applyUserID)) &&
                (!_Start.HasValue || p.ApplyStartTime <= _Start) &&
                (!_End.HasValue || p.ApplyEndTime >= _End), q => q.CreateTime);
            list.ForEach(p =>
            {
                result.Add(new CarApplyModels().ToModel(p));
            });

            return ToJson(result, list.TotalItemCount);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(string id)
        {
            try
            {
                CarApplyBLL bll = new CarApplyBLL();
                if (bll.Delete(Guid.Parse(id)))
                    return Content("OK");
                else
                    return Content("删除失败");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        #endregion

    }
}